package com.example.myapplication1.diyview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;


public class NoPaddingTextView extends View {

    private String text;
   private Context context;
    Paint paint = new Paint();
    public NoPaddingTextView(Context context) {
        super(context);
        this.context = context;
    }

    public NoPaddingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        paint.setColor(Color.RED);
        paint.setTextSize(dip2px(context,22));
    }

    public NoPaddingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        paint.setColor(Color.RED);
        paint.setTextSize(dip2px(context,20));
    }

    public void setText(String text) {

        this.text = text;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
       int width= (int) paint.measureText(text);
       setMeasuredDimension(width, dip2px(context,16));

    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
//         int bitmapwidht = bitmap.getWidth();
//         int height = bitmap.getHeight();
         Log.e("tag","---");

          canvas.drawText(text,dip2px(context,0),dip2px(context,16),paint);

    }
    /**
     * @return 返回指定的文字高度
     */
    public float getFontHeight(Paint paint) {

        Paint.FontMetrics fm = paint.getFontMetrics();    //文字基准线的下部距离-文字基准线的上部距离 = 文字高度
        return fm.descent - fm.ascent;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

